﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;

namespace Launcher
{
    public partial class Loading : Form
    {
        private string[] args = null;

        public Loading()
        {
            InitializeComponent();
        }       

        public Loading(string[] args)
            : this()
        {
            this.args = args;
        }

        private void Loading_Load(object sender, EventArgs e)
        {
            System.Threading.Tasks.Task.Run(() =>
            {
                Applications.KillProcess("Autoupgrade");

                System.Threading.Thread.Sleep(400);

                if (System.IO.File.Exists("ICSharpCode.WinFormsUI.Controls.dll.temp"))
                {
                    System.IO.File.Delete("ICSharpCode.WinFormsUI.Controls.dll");
                    System.IO.File.Move("ICSharpCode.WinFormsUI.Controls.dll.temp", "ICSharpCode.WinFormsUI.Controls.dll");
                }
                if (System.IO.File.Exists("ICSharpCode.WinFormsUI.dll.temp"))
                {
                    System.IO.File.Delete("ICSharpCode.WinFormsUI.dll");
                    System.IO.File.Move("ICSharpCode.WinFormsUI.dll.temp", "ICSharpCode.WinFormsUI.dll");
                }

                System.Threading.Thread.Sleep(400);

                if (args != null && args.Length > 0)
                {
                    string[] args_array = args[0].Split(',');
                    string startInfo = args_array[0].ToString();
                    args_array = args_array.Where(w => w != startInfo).ToArray();
                    Process process = ((args_array == null || args_array.Length > 0) ? Process.Start(startInfo) : Process.Start(startInfo, string.Join(",", args_array)));
                }

            }).ContinueWith((System.Threading.Tasks.Task task) => {

                try
                {
                    System.Threading.Thread.Sleep(400);
                    Application.Exit();
                }
                catch
                {                    
                    this.Invoke(new MethodInvoker(() =>
                    {
                        Application.Exit();
                    }));
                }                

            });
        }

    }
}
